<template>
  <div class="login-container">
    <div class="login-background"></div>
    <el-card class="login-card">
      <h2 class="login-title">登录</h2>
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" label-position="left">
        <el-form-item label="账号" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入账号"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"/>
        </el-form-item>
      </el-form>
      <div class="login-actions">
        <el-button type="primary" class="login-button" @click="handleLogin">登录</el-button>
      </div>
      <div class="login-footer">
        没有账号？<a @click="goRegister">立即注册</a>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref} from 'vue';
import {ElForm, ElFormItem, ElInput, ElButton, ElNotification} from 'element-plus';
import {useRoute, useRouter} from "vue-router";
import {apiPost} from "@/utils/api";
import {getTime} from "@/utils/time";
import {sessionStorage} from "@/utils/storage";

//获取el-form组件
let loginFormRef = ref()
//获取路由器
let $router = useRouter()
//路由对象
let $route = useRoute()

const loginForm = reactive({
  username: '111111',
  password: '111111',
});

const loginRules = {
  username: [
    {required: true, message: '请输入账号', trigger: 'blur'},
    {min: 6, message: '账号长度不能少于6位', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, message: '密码长度不能少于6位', trigger: 'blur'}
  ],
};

const handleLogin = async () => {
  await loginFormRef.value.validate();
  const {data} = await apiPost('/users/login', {...loginForm});
  sessionStorage.set("USER_TOKEN", data)
  let redirect = $route.query.redirect
  await $router.push({path: redirect || '/'})
  //登录成功提示信息
  ElNotification({
    type: 'success',
    message: '欢迎回来',
    title: `HI,${getTime()}好`,
  })
};
//跳转到注册页面
const goRegister = () => {
  $router.push({path: '/register'})
}
</script>
<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  overflow: hidden;

  .login-background {
    position: fixed; /* 使用固定定位 */
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: url('https://via.placeholder.com/1920x1080/09f/fff') no-repeat center center;
    background-size: cover;
    z-index: -1;
  }

  .login-card {
    width: 400px;
    padding: 30px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    text-align: center;
  }

  .login-title {
    margin-bottom: 30px;
  }

  .login-actions {
    display: flex;
    justify-content: center;
  }

  .login-button {
    width: 100%; /* 使按钮宽度与卡片宽度一致 */
  }
}
</style>